//
//  RegisterVC.m
//  代理端
//
//  Created by sliver on 15/12/11.
//  Copyright (c) 2015年 sliver. All rights reserved.
//

#import "RegisterVC.h"
#import "Unit.h"
#import "WXDataService.h"
@interface RegisterVC ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UIAlertViewDelegate,UIScrollViewDelegate>
{
    NSMutableArray *textFieldAry;
    UITextField *maintextField;
    NSArray *labAry1;
    NSArray *textFieldAry1;
    NSArray *labAry2;
    NSArray *textFieldAry2;
    NSArray *labAry3;
    NSArray *textFieldAry3;
    NSArray *delegateAry;
    
    UIActionSheet *_actionSheet;
    UIImageView *imgview;
    NSString *sex;
    //图片2进制路径
    NSString* filePath;
    //代理商类别
    int flag;
    NSInteger flag2;   //代理商的类别
    NSString *delegatestr; //代理商名字
    UITableView *tableview1; //主tableview
    UITableView *tableview2;//代理商类别的小view
    
    int picture; // 是否选择了图片
    
}
@end

@implementation RegisterVC

- (void)viewDidLoad {
    
    //注册键盘出现的通知
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShown:)
     
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    //注册键盘消失的通知
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden:)
     
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    flag = 1;
    flag2 = 4;
    picture = 0;
    labAry1 = @[@"账户名称",@"登录密码",@"确认登陆密码",@"支付密码",@"确认支付密码"];
    textFieldAry1 = @[@"请输入公司简称",@"登陆密码不能少于6位",@"请再次输入登陆密码",@"支付密码不能少于6位",@"请再次输入支付密码"];
    labAry2 = @[@"头像",@"代理商类别",@"公司名称",@"公司区域",@"公司地址",@"公司电话",@"公司联系人",@"公司联系人电话",@"收货地址"];
    textFieldAry2 = @[@"请选择头像",@"请选择代理商类别",@"请输入公司名称",@"公司区域 例xx省-xx市-xx区",@"请输入公司地址",@"请输入公司电话",@"请输入公司联系人",@"请输入公司联系人电话",@"请输入收货地址"];
    labAry3 = @[@"公司名称",@"公司地址",@"公司电话",@"税号",@"开户行",@"银行账号"];
    textFieldAry3 =@[@"请输入公司名称",@"请输入公司地址",@"请输入公司电话",@"请输入公司税号",@"请输入开户行",@"请输入银行账号"];
    delegateAry=@[@"省级代理商",@"市级代理商",@"县级代理商 （限山东）",@"采集客户",@"请选择代理商类别"];
    textFieldAry = [[NSMutableArray alloc]init];
    for(int i=0;i<18;i++){
        UITextField *textfieldtemp = [[UITextField alloc]init];
        [textFieldAry addObject:textfieldtemp];
    }
    [super viewDidLoad];
    [self loadNav];
    [self loadView1];
    // Do any additional setup after loading the view.
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
    
}
- (void)keyboardWasShown:(NSNotification*)aNotification

{
    
    //键盘高度
    
    CGRect keyBoardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSLog(@"%f",keyBoardFrame.size.height);
    
    tableview1.contentInset = UIEdgeInsetsMake(0, 0, keyBoardFrame.size.height, 0);
    
}
-(void)keyboardWillBeHidden:(NSNotification*)aNotification

{
    CGRect keyBoardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSLog(@"%f",keyBoardFrame.size.height);
    
    tableview1.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
}


#pragma mark - nav
-(void)loadNav{
    self.view.backgroundColor = DRINK_LIGHTGRAY_COLOR;
    UIView *redview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 20)];
    redview.backgroundColor = DRINK_RED_COLOR;
    [self.view addSubview:redview];
    
    UILabel *redLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, ScreenW, 40)];
    redLab.backgroundColor = DRINK_RED_COLOR;
    redLab.text = @"填写基本信息";
    redLab.textColor = [UIColor whiteColor];
    redLab.textAlignment =  NSTextAlignmentCenter;
    redLab.font = [UIFont boldSystemFontOfSize:17];
    [self.view addSubview:redLab];
    
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 20,44, 44)];
    backBtn.adjustsImageWhenHighlighted = NO;
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
}
#pragma mark - 中间view
-(void)loadView1{
    tableview1 = [[UITableView alloc]initWithFrame:CGRectMake(0, 60, ScreenW, ScreenH-160) style:UITableViewStyleGrouped];
    tableview1.delegate  = self;
    tableview1.dataSource = self;
    [self.view addSubview:tableview1];
    
    UIButton *commitBtn = [[UIButton alloc]initWithFrame:CGRectMake(80, ScreenH - 50, ScreenW - 160, 40)];
    commitBtn.backgroundColor = DRINK_RED_COLOR;
    [commitBtn setTitle:@"提交申请" forState:UIControlStateNormal];
    [commitBtn addTarget:self action:@selector(clicktijiao) forControlEvents:UIControlEventTouchUpInside];
    commitBtn.layer.masksToBounds = YES;
    commitBtn.layer.cornerRadius = 5;
    [self.view addSubview:commitBtn];
}
#pragma mark - 点击提交
-(void)clicktijiao{
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    NSMutableArray *fieldStrAry = [[NSMutableArray alloc]init];
    for(int i=0 ;i<18;i++){
        UITextField *textfield = [textFieldAry objectAtIndex:i];
        [fieldStrAry addObject:textfield.text];
    }
    if(![[fieldStrAry objectAtIndex:1] isEqualToString:[fieldStrAry objectAtIndex:2]] || ![[fieldStrAry objectAtIndex:3] isEqualToString:[fieldStrAry objectAtIndex:4]]){
        UIAlertView *deleAlertView=[[UIAlertView alloc]initWithTitle:nil message:@"密码输入不一致,请重新输入" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [deleAlertView show];
        return;
    }
    if([(NSString *)[fieldStrAry objectAtIndex:1] length] <6 || [(NSString *)[fieldStrAry objectAtIndex:3] length] <6){
        UIAlertView *deleAlertView=[[UIAlertView alloc]initWithTitle:nil message:@"密码不能少于6位" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [deleAlertView show];
        return;
    }
    [params setObject:[fieldStrAry objectAtIndex:0] forKey:@"account"];
    [params setObject:[fieldStrAry objectAtIndex:1] forKey:@"login_pass"];
    [params setObject:[fieldStrAry objectAtIndex:3] forKey:@"pay_pass"];
    [params setObject:[NSString stringWithFormat:@"%lu",flag2+1] forKey:@"level"];
    [params setObject:[fieldStrAry objectAtIndex:5] forKey:@"company_name"];
    [params setObject:[fieldStrAry objectAtIndex:6] forKey:@"company_district"];
    [params setObject:[fieldStrAry objectAtIndex:7] forKey:@"company_address"];
    [params setObject:[fieldStrAry objectAtIndex:8] forKey:@"company_tel"];
    [params setObject:[fieldStrAry objectAtIndex:9] forKey:@"company_contact_name"];
    [params setObject:[fieldStrAry objectAtIndex:10] forKey:@"company_contact_tel"];
    [params setObject:[fieldStrAry objectAtIndex:11] forKey:@"deliver_address"];
    [params setObject:[fieldStrAry objectAtIndex:12] forKey:@"t_company_name"];
    [params setObject:[fieldStrAry objectAtIndex:13] forKey:@"t_company_address"];
    [params setObject:[fieldStrAry objectAtIndex:14] forKey:@"t_company_tel"];
    [params setObject:[fieldStrAry objectAtIndex:15] forKey:@"tax"];
    [params setObject:[fieldStrAry objectAtIndex:16] forKey:@"open_card"];
    [params setObject:[fieldStrAry objectAtIndex:17] forKey:@"bankcard"];
    
    [MyMbd addHudToView:self.view];
    
    [WXDataService requestWithURL:@"mobile/agency/registerAgency.jhtml" params:params httpMethod:@"POST" block:^(id result, NSString *success, NSString *msg) {
        BOOL suc =[success boolValue];
        if (suc == 0 ) {
            UIAlertView *deleAlertView=[[UIAlertView alloc]initWithTitle:nil message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [deleAlertView show];
            return;
        }else if(suc == 1){
            UIAlertView *deleAlertView=[[UIAlertView alloc]initWithTitle:nil message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [deleAlertView show];
            if (picture == 1) {
                [self loadImageData:result[@"id_"]];
            }
            
        }
    }failblock:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 20)];
    view.backgroundColor = DRINK_LIGHTGRAY_COLOR;
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, 20)];
    lab.textColor = [UIColor blackColor];
    lab.font = [UIFont boldSystemFontOfSize:14];
    switch (section) {
        case 0:
            lab.text = @"账户信息";
            break;
        case 1:
            lab.text = @"基本信息";
            break;
        case 2:
            lab.text = @"开票信息";
            break;
        default:
            break;
    }
    [view addSubview:lab];
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == tableview2) {
        return 0;
    }
    return 20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == tableview2) {
        return 30;
    }
    if (indexPath.section == 1 && indexPath.row == 0) {
        return 50;
    }
    if (flag == -1) {
        if (indexPath.section == 1 && indexPath.row == 1) {
            return 150;
        }
    }
    return 30;
}
#pragma mark - 返回上界面
-(void)clickBack{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView == tableview2) {
        return 1;
    }
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == tableview2) {
        return 4;
    }
    switch (section) {
        case 0:
            return 5;
            break;
        case 1:
            return 9;
            break;
        case 2:
            return 6;
            
        default:
            break;
    }
    return 0;
    
}
#pragma mark - 点击tableview
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == tableview2) {
        flag2 = indexPath.row;
        flag = -flag;
        delegatestr = [delegateAry objectAtIndex:indexPath.row];
        NSIndexPath *path = [NSIndexPath indexPathForRow:1 inSection:1];
        [tableview1 reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationNone];
    }else if(tableView == tableview1){
        if (indexPath.section == 1 && indexPath.row == 1) {
            flag = -flag;
            NSIndexPath *path = [NSIndexPath indexPathForRow:1 inSection:1];
            [tableview1 reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationNone];
        }
    }else{
        
    }
}
#pragma mark - cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell;
    UILabel *lab1 = [[UILabel alloc]initWithFrame:CGRectMake(5, 0, 120, 30)];
    lab1.textColor = [UIColor grayColor];
    lab1.font = [UIFont boldSystemFontOfSize:15];
    UILabel *lab2 = [[UILabel alloc]initWithFrame:CGRectMake(120, 0, 150, 30)];
    lab2.tag = 1;
    lab2.textColor = [UIColor grayColor];
    lab2.font = [UIFont systemFontOfSize:13];
    
    NSString *cellStr = [NSString stringWithFormat:@"cell-%lu%lu",indexPath.section,indexPath.row];
    cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    if (tableView == tableview2) {
        cell = [[UITableViewCell alloc]init];
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 280, 30)];
        lab.font = [UIFont systemFontOfSize:13];
        lab.textColor = [UIColor grayColor];
        lab.text = [delegateAry objectAtIndex:indexPath.row];
        [cell.contentView addSubview:lab];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        return cell;
    }
    if(cell == nil){
        cell=  [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellStr];
        
        maintextField = [[UITextField alloc]initWithFrame:CGRectMake(120, 0, ScreenW  -120, 30)];
        maintextField.textColor = [UIColor grayColor];
        maintextField.delegate = self;
        maintextField.font = [UIFont systemFontOfSize:13.0 ];
        maintextField.textAlignment = NSTextAlignmentLeft;
        maintextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        maintextField.keyboardType = UIKeyboardTypeDefault;
        maintextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        maintextField.returnKeyType = UIReturnKeyDone;
        maintextField.delegate= self;
        switch (indexPath.section) {
            case 0:
                lab1.text = [labAry1 objectAtIndex:indexPath.row];
                [cell.contentView addSubview:lab1];
                maintextField.placeholder = [textFieldAry1 objectAtIndex:indexPath.row];
                [textFieldAry replaceObjectAtIndex:indexPath.row withObject:maintextField];
                [cell.contentView addSubview:maintextField];
                break;
            case 1:
                lab1.text = [labAry2 objectAtIndex:indexPath.row];
                [cell.contentView addSubview:lab1];
                if (indexPath.row == 0) {
                    lab1.frame = CGRectMake(5, 0, 120, 50);
                    imgview = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenW - 55, 5, 45, 40)];
                    imgview.userInteractionEnabled =YES;
                    imgview.image = [UIImage imageNamed:@"矩形-4"];
                    //单击手势
                    UITapGestureRecognizer *sigleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(signalTapAction:)];
                    //设置点击手指的根数
                    sigleTap.numberOfTouchesRequired = 1;
                    //点击屏幕次数
                    sigleTap.numberOfTapsRequired = 1;
                    [imgview addGestureRecognizer:sigleTap];
                    [cell.contentView addSubview:imgview];
                    break;
                }
                if (indexPath.row == 1) {
                    lab2.text =[delegateAry objectAtIndex:flag2];
                    [cell.contentView addSubview:lab2];
                    if (flag == -1) {
                        tableview2=[[UITableView alloc]initWithFrame:CGRectMake(120, 30, ScreenW - 120, 120)];
                        tableview2.delegate = self;
                        tableview2.dataSource =self;
                        tableview2.scrollEnabled = NO;
                        [cell.contentView addSubview:tableview2];
                        break;
                    }
                    break;
                }
                maintextField.placeholder = [textFieldAry2 objectAtIndex:indexPath.row];
                [textFieldAry replaceObjectAtIndex:indexPath.row+3 withObject:maintextField];
                [cell.contentView addSubview:maintextField];
                if (indexPath.row == 5 || indexPath.row == 7) {
                    maintextField.keyboardType = UIKeyboardTypeNumberPad;
                }
                break;
            case 2:
                lab1.text = [labAry3 objectAtIndex:indexPath.row];
                [cell.contentView addSubview:lab1];
                maintextField.placeholder = [textFieldAry3 objectAtIndex:indexPath.row];
                [textFieldAry replaceObjectAtIndex:indexPath.row+12 withObject:maintextField];
                [cell.contentView addSubview:maintextField];
                if (indexPath.row == 2) {
                    maintextField.keyboardType = UIKeyboardTypeNumberPad;
                }
                break;
            default:
                break;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (indexPath.row == 1 && indexPath.section == 1){
        UILabel *lab = (UILabel *)[self.view viewWithTag:1];
        lab.text =[delegateAry objectAtIndex:flag2];
    }
    return cell;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [maintextField resignFirstResponder];
    return YES;
    
}
//-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//{
//    [super touchesBegan:touches withEvent:event];
//    [maintextField resignFirstResponder];
//}
#pragma mark - 单击加载图片
-(void)signalTapAction:(UITapGestureRecognizer *)tap{
    [self imageBtnClick];
}
//上传头像
-(void)loadImageData:(NSString *)ageid{
    NSMutableDictionary *params =[[NSMutableDictionary alloc]init];
    [params setObject:@"image.jpeg" forKey:@"file_"];
    [params setObject:ageid  forKey:@"id_"];
    //    [params setObject:@"5" forKey:@"flag"];
    NSLog(@"-----file ==%@",filePath);
    [WXDataService postImageWithURL:@"mobile/user/uploadAvatar.jhtml" imagePathFile:filePath params:params httpMethod:@"POST" block:^(id result, NSString *success, NSString *msg) {
        NSLog(@"vvvvvvvvvvvvvvvvvv%@",msg);
        [MyMbd hidenHudFromView:self.view];
    }];
}
-(void)passPressed
{
    NSLog(@"跳过");
}
- (void)sgChange:(UISegmentedControl *)sg{
    //找到目前点第几个
    sex =[NSString stringWithFormat:@"%ld",(long)sg.selectedSegmentIndex];
    
    //获取文字
    NSString *title = [sg titleForSegmentAtIndex:sg.selectedSegmentIndex];
    NSLog(@"%@",title);
    
}

//点击头像进入这里
-(void)imageBtnClick
{
    _actionSheet = [[UIActionSheet alloc]
                    initWithTitle:nil
                    delegate:self
                    cancelButtonTitle:@"取消"
                    destructiveButtonTitle:nil
                    otherButtonTitles: @"拍照", @"从相册选择",nil];
    _actionSheet.tag = 1000;
    [_actionSheet showInView:self.view];
}

#pragma mark --UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(actionSheet.tag == 1000){
        //呼出的菜单按钮点击后的响应
        //    if (buttonIndex == actionSheet.cancelButtonIndex)
        //    {
        //        NSLog(@"取消");
        //    }
        
        switch (buttonIndex)
        {
            case 0:  //打开照相机拍照
                [self takePhoto];
                break;
                
            case 1:  //打开本地相册
                [self LocalPhoto];
                break;
        }
    }
    
    
}
//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        //        [self presentModalViewController:picker animated:YES];
        [self presentViewController:picker animated:YES completion:nil];
    }else
    {
        //        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
    }
}
//打开本地相册
-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    //    [self presentModalViewController:picker animated:YES];
    [self presentViewController:picker animated:YES completion:nil];
}

//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    picture = 1;
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage * image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        image = [self fixOrientation:image];
        NSData *data;
        //        if (UIImagePNGRepresentation(image) == nil)
        //        {
        data = UIImageJPEGRepresentation(image, 0.001);
        //        }
        //        else
        //        {
        //            data = UIImagePNGRepresentation(image);
        //        }
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        
        //得到选择后沙盒中图片的完整路径
        filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];
        
        //关闭相册界面
        //        [picker dismissModalViewControllerAnimated:YES];
        [picker dismissViewControllerAnimated:YES completion:nil];
        
        //创建一个选择后图片的小图标放在下方
        //类似微薄选择图后的效果
        //        UIImageView *smallimage = [[UIImageView alloc] initWithFrame:
        //                                   CGRectMake(50, 120, 40, 40)];
        
        //        smallimage.image = image;
        imgview.image = image;
        //加在视图中
        //        [self.view addSubview:smallimage];
    }
    //  [self loadImageData];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //    NSLog(@"您取消了选择图片");
    //    [picker dismissModalViewControllerAnimated:YES];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark 图片方向处理
- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
